<template>
  <div class="login-form">
    <n-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      size="large"
      :show-label="false"
    >
      <n-form-item path="username">
        <n-input
          v-model:value="formData.username"
          placeholder="请输入用户名或邮箱"
          :disabled="loading"
          @keydown.enter="handleSubmit"
        >
          <template #prefix>
            <n-icon :size="18">
              <PersonOutline />
            </n-icon>
          </template>
        </n-input>
      </n-form-item>

      <n-form-item path="password">
        <n-input
          v-model:value="formData.password"
          type="password"
          placeholder="请输入密码"
          :disabled="loading"
          show-password-on="click"
          @keydown.enter="handleSubmit"
        >
          <template #prefix>
            <n-icon :size="18">
              <LockClosedOutline />
            </n-icon>
          </template>
        </n-input>
      </n-form-item>

      <!-- 点击验证码 -->
      <n-form-item>
        <ClickCaptcha
          @update:captcha-id="updateCaptchaId"
          @update:captcha-info="updateCaptchaInfo"
          @verified="handleCaptchaVerified"
          :disabled="loading"
        />
      </n-form-item>

      <div class="form-options">
        <n-checkbox v-model:checked="formData.keep" :disabled="loading">
          记住登录
        </n-checkbox>
        <n-button
          text
          type="primary"
          :disabled="loading"
          @click="$emit('forgot-password')"
        >
          忘记密码？
        </n-button>
      </div>

      <n-button
        type="primary"
        size="large"
        block
        :loading="loading"
        @click="handleSubmit"
        class="submit-btn"
      >
        登录
      </n-button>
    </n-form>

    <div class="form-footer">
      <n-text depth="3">还没有账号？</n-text>
      <n-button
        text
        type="primary"
        :disabled="loading"
        @click="$emit('switch-to-register')"
      >
        立即注册
      </n-button>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive } from 'vue'
import { useMessage } from 'naive-ui'
import { useUserStore } from '@/stores/user'
import { commonRules } from '@/utils/validation'
import { generateRandomString } from '@/utils/auth'
import ClickCaptcha from '@/components/common/ClickCaptcha.vue'
import type { FormInst } from 'naive-ui'
import type { LoginParams } from '@/types/user'
import {
  PersonOutline,
  LockClosedOutline
} from '@vicons/ionicons5'

interface Emits {
  (e: 'success'): void
  (e: 'switch-to-register'): void
  (e: 'forgot-password'): void
}

const emit = defineEmits<Emits>()
const message = useMessage()
const userStore = useUserStore()

// 表单引用
const formRef = ref<FormInst | null>(null)

// 表单数据
const formData = reactive<LoginParams>({
  tab: 'login',
  username: '',
  password: '',
  keep: false,
  captcha: '',
  captchaId: generateRandomString(),
  captchaInfo: ''
})

// 状态
const loading = ref(false)
const captchaVerified = ref(false)

// 表单验证规则
const formRules = {
  username: commonRules.loginAccount,
  password: commonRules.password
}

// 更新验证码ID
const updateCaptchaId = (id: string) => {
  formData.captchaId = id
}

// 更新验证码信息
const updateCaptchaInfo = (info: string) => {
  formData.captchaInfo = info
}

// 处理验证码验证成功
const handleCaptchaVerified = (verified: boolean) => {
  captchaVerified.value = verified
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return

  // 检查验证码是否已验证
  if (!captchaVerified.value) {
    message.error('请先完成验证码验证')
    return
  }

  try {
    await formRef.value.validate()
    loading.value = true

    await userStore.login(formData)
    emit('success')
  } catch (error: any) {
    console.error('登录失败:', error)
    message.error(error.message || '登录失败，请重试')
  } finally {
    loading.value = false
  }
}
</script>

<style scoped>
.login-form {
  padding: 8px 0;
}



.form-options {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin: 16px 0;
}

.submit-btn {
  margin-top: 8px;
  border-radius: 8px;
  font-weight: 500;
}

.form-footer {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 8px;
  margin-top: 24px;
  padding-top: 16px;
  border-top: 1px solid var(--n-border-color);
}

/* 响应式调整 */
@media (max-width: 480px) {
  .captcha-container {
    gap: 8px;
  }
  
  .captcha-image {
    width: 80px;
    height: 36px;
  }
  
  .form-options {
    margin: 12px 0;
  }
  
  .form-footer {
    margin-top: 20px;
    padding-top: 12px;
  }
}
</style>
